import json
import time

from django.core import serializers
from django.forms import model_to_dict
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from pymysql import DatabaseError

from bookDisplay.models import books
from utils.apiResponse import ApiResponse
from .models import User, Favorite

from django.middleware.csrf import get_token


def get_csrf_token(request):
    token = get_token(request)
    return JsonResponse({'csrfToken': token})


# Create your views here.
@csrf_exempt
def login(request):
    try:
        data = json.loads(request.body)
        phone = data.get('phone')
        password = data.get('password')
        user = User.objects.filter(phone=phone, password=password)
        if user.count() == 0:
            raise User.DoesNotExist('用户不存在')
        user = list(user.values())

        return ApiResponse(data=user, message="登录成功", status=200, success=True)
    except User.DoesNotExist as e:
        return ApiResponse(message=str('用户不存在'), success=False, status=500)
    except Exception as e:
        return ApiResponse(message=str(e), success=False, status=500)


@csrf_exempt
def register(request):
    try:
        data = json.loads(request.body)
        phone = data.get('phone')
        password = data.get('password')
        print(phone, password)
        user = User.objects.filter(phone=phone)
        if not user:
            user = User(username='', nickname='', password=password, avatar='static/image/default.png', phone=phone,
                        email='',
                        level=1)
            user.save()
            return ApiResponse(message="注册成功", status=200, success=True)
        else:
            raise ValueError('手机号已注册')
    except json.JSONDecodeError as e:
        # 捕获 JSON 解码错误
        return ApiResponse(message="无效的 JSON 格式", success=False, status=400)
    except DatabaseError as e:
        # 捕获数据库相关错误（如唯一性约束失败等）
        return ApiResponse(message="数据库错误，请稍后再试", success=False, status=500)
    except ValueError as e:
        return ApiResponse(message=str(e), success=False, status=400)
    except Exception as e:
        # 捕获其他未知错误
        return ApiResponse(message=str(e), success=False, status=500)


@csrf_exempt
def get_favorite(request):
    try:
        data = json.loads(request.body)
        userId = int(data.get('userId'))
        bookId = int(data.get('bookId'))
        if not userId or not bookId:
            raise ValueError('参数错误')
        user = User.objects.get(id=userId)
        if not user:
            raise ValueError('用户不存在')
        book = books.objects.get(id=bookId)
        if not book:
            raise ValueError('书籍不存在')

        favorite = Favorite.objects.filter(user=user, book=book)
        favorite = list(favorite.values())
        return ApiResponse(data=favorite, message="获取收藏成功", status=200, success=True)
    except User.DoesNotExist as e:
        return ApiResponse(message=str(e), success=False, status=404)
    except ValueError as e:
        return ApiResponse(message=str(e), success=False, status=400)
    except Exception as e:
        return ApiResponse(message=str(e), success=False, status=500)


@csrf_exempt
def add_favorite(request):
    try:
        data = json.loads(request.body)
        userId = int(data.get('userId'))
        bookId = int(data.get('bookId'))
        font_size = int(data.get('font_size'))
        chapter_number = int(data.get('chapter_number'))
        page_number = int(data.get('page_number'))

        print(userId, bookId, font_size, chapter_number, page_number)

        if not userId or not bookId or not font_size or not chapter_number:
            raise ValueError('参数错误')
        user = User.objects.get(id=userId)
        if not user:
            raise ValueError('用户不存在')
        book = books.objects.get(id=bookId)
        if not book:
            raise ValueError('书籍不存在')
        favorite = Favorite.objects.filter(user=user, book=book)
        if favorite.count() > 0:
            raise ValueError('已收藏')
        favorite = Favorite(user=user, book=book, font_size=font_size, chapter_number=chapter_number,
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                            page_number=page_number)
        favorite.save()
        return ApiResponse(message="收藏成功", status=200, success=True)
    except User.DoesNotExist as e:
        return ApiResponse(message=str(e), success=False, status=404)
    except ValueError as e:
        return ApiResponse(message=str(e), success=False, status=400)
    except Exception as e:
        return ApiResponse(message=str(e), success=False, status=500)


@csrf_exempt
def remove_favorite(request):
    try:
        data = json.loads(request.body)
        userId = int(data.get('userId'))
        bookId = int(data.get('bookId'))
        if not userId or not bookId:
            raise ValueError('参数错误')
        user = User.objects.get(id=userId)
        if not user:
            raise ValueError('用户不存在')
        book = books.objects.get(id=bookId)
        if not book:
            raise ValueError('书籍不存在')
        favorite = Favorite.objects.filter(user=user, book=book)
        if favorite.count() == 0:
            raise ValueError('未收藏')
        favorite.delete()
        return ApiResponse(message="取消收藏成功", status=200, success=True)
    except User.DoesNotExist as e:
        return ApiResponse(message=str(e), success=False, status=404)
    except ValueError as e:
        return ApiResponse(message=str(e), success=False, status=400)
    except Exception as e:
        return ApiResponse(message=str(e), success=False, status=500)


@csrf_exempt
def update_favorite(request):
    try:
        data = json.loads(request.body)
        userId = int(data.get('userId'))
        bookId = int(data.get('bookId'))
        font_size = int(data.get('font_size'))
        chapter_number = int(data.get('chapter_number'))
        page_number = int(data.get('page_number'))
        if not userId or not bookId or not font_size or not chapter_number:
            raise ValueError('参数错误')
        user = User.objects.get(id=userId)
        if not user:
            raise ValueError('用户不存在')
        book = books.objects.get(id=bookId)
        if not book:
            raise ValueError('书籍不存在')
        favorite = Favorite.objects.filter(user=user, book=book)
        if favorite.count() == 0:
            raise ValueError('未收藏')
        favorite = favorite.first()
        favorite.font_size = font_size
        favorite.chapter_number = chapter_number
        favorite.page_number = page_number
        favorite.save()
        return ApiResponse(message="更新收藏成功", status=200, success=True)
    except User.DoesNotExist as e:
        return ApiResponse(message=str(e), success=False, status=404)
    except ValueError as e:
        return ApiResponse(message=str(e), success=False, status=400)
    except Exception as e:
        return ApiResponse(message=str(e), success=False, status=500)


@csrf_exempt
def get_user_all_favorite(request):
    try:
        data = json.loads(request.body)
        userId = int(data.get('userId'))
        if not userId:
            raise ValueError('参数错误')
        user = User.objects.get(id=userId)
        if not user:
            raise ValueError('用户不存在')

        # 查询 Favorite 表，并通过 select_related 连接 books 表
        # favorites = Favorite.objects.filter(user=user).select_related('book')
        # 查询并只返回需要的字段
        favorites = Favorite.objects.filter(user=user).select_related('book').values(
            'book_id',
            'user_id',
            'font_size',
            'chapter_number',
            'page_number',
            'book__novel_number',
            'book__book_cover',
            'book__book_name',
            'book__total_chapter'
        )
        favorites = list(favorites)
        return ApiResponse(data=favorites, message="获取收藏成功", status=200, success=True)
    except User.DoesNotExist as e:
        return ApiResponse(message=str(e), success=False, status=404)
    except ValueError as e:
        return ApiResponse(message=str(e), success=False, status=400)
    except Exception as e:
        return ApiResponse(message=str(e), success=False, status=500)
